package com.team.recruitment_management_system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.team.recruitment_management_system.mapper.SysUserMapper;
import com.team.recruitment_management_system.pojo.dto.auth.EmailAndCaptchaDto;
import com.team.recruitment_management_system.pojo.dto.user.AddUserInfoDto;
import com.team.recruitment_management_system.pojo.dto.user.ChangeEmailDto;
import com.team.recruitment_management_system.pojo.dto.user.ChangePwdDto;
import com.team.recruitment_management_system.pojo.entity.SysUser;
import com.team.recruitment_management_system.pojo.vo.UserInfoVo;
import com.team.recruitment_management_system.service.SysUserService;
import com.team.recruitment_management_system.util.JwtHelper;
import com.team.recruitment_management_system.util.MD5Util;
import com.team.recruitment_management_system.util.result.Result;
import com.team.recruitment_management_system.util.result.ResultCodeEnum;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

import static com.team.recruitment_management_system.pojo.constant.EmailConstant.*;

/**
* @author 86147
* @description 针对表【sys_user(用户表)】的数据库操作Service实现
* @createDate 2024-03-21 20:28:40
*/
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser>
    implements SysUserService{

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private JwtHelper jwtHelper;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Override
    public Result<Void> addUserInfo(AddUserInfoDto addUserInfoDto, String token) {
        Integer userId = jwtHelper.getUserId(token);
        SysUser sysUser = this.getById(userId);
        BeanUtils.copyProperties(addUserInfoDto,sysUser);
        this.updateById(sysUser);
        return Result.putOk(null);
    }

    @Override
    public Result<Void> changePassword(ChangePwdDto changePwdDto,String token) {
        //账号查询
        int userId = jwtHelper.getUserId(token);
        SysUser user = this.getById(userId);
        //账号密码判断
        if (!StringUtils.isEmpty(user.getPassword()) && user.getPassword().equals(MD5Util.encrypt(changePwdDto.getPassword()))) {
            //账号密码正确
            // 使用 LambdaUpdateWrapper 修改指定属性
            LambdaUpdateWrapper<SysUser> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            lambdaUpdateWrapper.eq(SysUser::getId, user.getId())
                    .set(SysUser::getPassword, MD5Util.encrypt(changePwdDto.getNewPassword()));
            this.update(lambdaUpdateWrapper); // 执行更新操作
            return Result.ok(null, "修改成功！");
        }
        //密码错误
        return Result.build(null, ResultCodeEnum.PASSWORD_ERROR);
    }

    @Override
    public Result<Void> bindingEmail(EmailAndCaptchaDto emailAndCaptchaDto, String token) {
        SysUser user = sysUserMapper.getUserByEmail(emailAndCaptchaDto.getEmail());
        if (user != null) {
            return Result.build(null, ResultCodeEnum.EMAIL_USED);
        }

        String captcha = (String) redisTemplate.opsForValue().get(EMAIL_BINDING_EM_PRIM + emailAndCaptchaDto.getEmail());
        //判断
        if (captcha != null && !StringUtils.isEmpty(emailAndCaptchaDto.getCaptcha()) && captcha.equalsIgnoreCase(emailAndCaptchaDto.getCaptcha())) {
            // 获取请求头中的令牌
            int userId = jwtHelper.getUserId(token);
            LambdaUpdateWrapper<SysUser> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(SysUser::getId, userId)
                    .set(SysUser::getEmail, emailAndCaptchaDto.getEmail());
            this.update(updateWrapper);
            return Result.ok(null, "邮箱成功绑定！");
        }
        //验证码错误
        return Result.build(null, ResultCodeEnum.CAPTCHA_ERROR);
    }

    @Override
    public Result<Void> verifyOldEmail(EmailAndCaptchaDto emailAndCaptchaDto,String token) {
        int userId = jwtHelper.getUserId(token);
        SysUser user = sysUserMapper.getUserByEmail(emailAndCaptchaDto.getEmail());
        if (user == null || userId != user.getId()) {
            return Result.build(null, ResultCodeEnum.ILLEGAL_OPERATION);
        }
        String captcha = (String) redisTemplate.opsForValue().get(EMAIL_CHANGE_EM_OLD_PRIM + emailAndCaptchaDto.getEmail());
        //判断
        if (captcha != null && !StringUtils.isEmpty(emailAndCaptchaDto.getCaptcha()) && captcha.equalsIgnoreCase(emailAndCaptchaDto.getCaptcha())) {
            redisTemplate.opsForValue().set(EMAIL_VERIFY_OLD_SUCCESS_PRIM+userId,true,15L, TimeUnit.MINUTES);
            return Result.ok(null, "旧邮箱验证成功！");
        }
        //验证码错误
        return Result.build(null, ResultCodeEnum.CAPTCHA_ERROR);
    }

    @Override
    public Result<Void> changeEmail(ChangeEmailDto changeEmailDto, String token) {
        // 获取请求头中的令牌
        int userId = jwtHelper.getUserId(token);
        SysUser user = getUserByEmail(changeEmailDto.getOldEmail());
        if (user == null || userId != user.getId()) {
            return Result.build(null, ResultCodeEnum.ILLEGAL_OPERATION);
        }

        String captcha = (String) redisTemplate.opsForValue().get(EMAIL_CHANGE_EM_NEW_PRIM + changeEmailDto.getEmail());
        //判断
        if (captcha != null && !StringUtils.isEmpty(changeEmailDto.getCaptcha()) && captcha.equalsIgnoreCase(changeEmailDto.getCaptcha())) {
            if (changeEmailDto.getEmail().equals(changeEmailDto.getOldEmail())) {
                return Result.build(null, 500, "当前的新旧邮箱相同");
            }

            LambdaUpdateWrapper<SysUser> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(SysUser::getId, userId)
                    .set(SysUser::getEmail, changeEmailDto.getEmail());
            this.update(updateWrapper);
            return Result.ok(null, "新邮箱修改成功！");
        }
        //验证码错误
        return Result.build(null, ResultCodeEnum.CAPTCHA_ERROR);
    }

    @Override
    public Result<Void> changePhone(String newPhone,String token) {
        int userId = jwtHelper.getUserId(token);
        SysUser user = this.getById(userId);
        user.setPhone(newPhone);
        this.updateById(user);
        return Result.ok(null,"修改成功");
    }

    @Override
    public Result<Void> changeAvatar(String newAvatar,String token) {
        int userId = jwtHelper.getUserId(token);
        SysUser user = this.getById(userId);
        user.setAvatar(newAvatar);
        this.updateById(user);
        return Result.ok(null,"修改成功");
    }

    @Override
    public Result<Void> cancelAccount(String token) {
        int userId = jwtHelper.getUserId(token);
        this.removeById(userId);
        return Result.ok(null,"注销成功");
    }

    @Override
    public Result<UserInfoVo> getUserInfo(String token) {
        int userId = jwtHelper.getUserId(token);
        SysUser user = this.getById(userId);
        if(user != null){
            UserInfoVo userInfoVo = new UserInfoVo();
            BeanUtils.copyProperties(user,userInfoVo);
            String email = user.getEmail();
            if (email != null) {
                userInfoVo.setEmail(email.substring(0, 2) + "***" + email.substring(email.indexOf("@")));
            }
            return Result.ok(userInfoVo);
        }
        return Result.build(null,ResultCodeEnum.ILLEGAL_OPERATION);
    }

        public SysUser getUserByEmail(String email) {
            LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysUser::getEmail, email);
            return this.getOne(queryWrapper);
        }
}




